
package edu.upn.sigemfi.plt.bc;

import edu.upn.sigemfi.plt.be.Cliente;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Gerard
 */
public class ClienteDelegate {

    private ClienteFacadeLocal local;

    public ClienteDelegate() {
        local = lookupClienteFacade();
    }

    public void crear(Cliente cliente) throws Exception{
        try {
            local.create(cliente);
        } catch (Exception e) {
            local = lookupClienteFacade();
            throw new Exception("Crear Cliente. " + e.getMessage(),e);
        }
    }

    public void editar(Cliente cliente) throws Exception{
        try {
            local.edit(cliente);
        } catch (Exception e) {
            local = lookupClienteFacade();
            throw new Exception("Editar Cliente. " + e.getMessage(),e);
        }
    }

    public void eliminar(Cliente cliente) throws Exception{
        try {
            local.remove(cliente);
        } catch (Exception e) {
            local = lookupClienteFacade();
            throw new Exception("Eliminar Cliente. " + e.getMessage(),e);
        }
    }

    public Cliente buscar(Long codigo) throws Exception{
        try {
            return local.find(codigo);
        } catch (Exception e) {
            local = lookupClienteFacade();
            throw new Exception("Buscar Cliente. " + e.getMessage(),e);
        }
    }

    public List<Cliente> listar() throws Exception{
        try {
            return local.findAll();
        } catch (Exception e) {
            local = lookupClienteFacade();
            throw new Exception("Listar Cliente. " + e.getMessage(),e);
        }
    }

    private ClienteFacadeLocal lookupClienteFacade() {
        try {
            Context c = new InitialContext();
            return (ClienteFacadeLocal) c.lookup("java:comp/env/ClienteFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    

}
